package com.lxinet.jeesns.core.handler;

import com.lxinet.jeesns.core.utils.Const;
import com.lxinet.jeesns.core.utils.ContextHolderUtil;
import com.lxinet.jeesns.core.utils.DES3Util;
import com.lxinet.jeesns.core.utils.JeesnsConfig;
import com.lxinet.jeesns.core.utils.StringUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.net.URL;
import java.security.Key;
import javax.crypto.Cipher;
import javax.servlet.http.HttpServletRequest;
import sun.misc.BASE64Decoder;

public class LicHandler
{
  private static final String ALGORITHM = "RSA";
  public static boolean authorized = false;
  
  public static void init()
  {
    ObjectInputStream ois = null;
    try
    {
      if (StringUtils.isNotBlank(Const.licKey))
      {
        File file = new File(JeesnsConfig.class.getClassLoader().getResource("").getPath() + DES3Util.des3DecodeECB("Fda2e92eSvjFv/rUxFVrTw=="));
        if (file.exists())
        {
          ois = new ObjectInputStream(new FileInputStream(file));
          Key privateKey = (Key)ois.readObject();
          Cipher cipher = Cipher.getInstance("RSA");
          cipher.init(2, privateKey);
          BASE64Decoder decoder = new BASE64Decoder();
          byte[] b1 = decoder.decodeBuffer(Const.licKey);
          byte[] b = cipher.doFinal(b1);
          String result = new String(b);
          String domain = result.substring(47, result.length() - 18);
          System.out.println(domain);
          String currDomain = ContextHolderUtil.getRequest().getServerName();
          if (currDomain.indexOf(domain) > -1) {
            authorized = true;
          } else {
            authorized = false;
          }
        }
        else
        {
          authorized = false;
        }
      }
      else
      {
        authorized = false;
      }
      return;
    }
    catch (Exception e)
    {
      e.printStackTrace();
      authorized = false;
    }
    finally
    {
      try
      {
        Const.setLic(authorized);
        if (ois != null) {
          ois.close();
        }
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
    }
  }
}
